package com.syj.common.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by rankawin on 2017/2/13.
 */
public class FileUtil {

    private static final String DEFAULT_IMAGE_PATH = "/upload/img/";

    public static String uploadFile(MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile != null) {
            try {
                request.setCharacterEncoding("utf-8");
                String basePath = request.getSession().getServletContext().getRealPath(DEFAULT_IMAGE_PATH);
                String fileName = multipartFile.getOriginalFilename();
                String fileType = fileName.lastIndexOf(".") >= 0 ? fileName.substring(fileName.lastIndexOf(".")) : "";
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMdd");
                fileName = sDateFormat.format(new Date()) + (int) ((1 + Math.random()) * 1000000000) + fileType;
                String filePath = basePath + "/" + fileName;
                File file = new File(filePath);
                multipartFile.transferTo(file);
                return DEFAULT_IMAGE_PATH + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
